<template>
    <div>
        <el-dialog
            title="上传发票"
            :visible.sync="dialogVisible"
            width="80%"
            @open="dialogOpen"
            @close="handleClose"
            class='header'
        >
            <div class="e-table">
                <div
                    class="top"
                    v-if="
                        attachTableData.length ||
                        (!attachTableData.length && !isView)
                    "
                >
                    <div class="left" >
                        <el-upload
                            v-if="!isView"
                            class="upload-demo"
                            :action="uploadUrl"
                            :headers="{
                                token: userInfo.token,
                                org: encodeURIComponent(
                                    JSON.stringify(userInfo.orgInfo)
                                )
                            }"
                            :data="{
                                bucketName,
                                relationId,
                                orgCode
                            }"
                            :before-upload="beforeAvatarUpload"
                            multiple
                            :accept="accept"
                            :on-success="attachOnSuccess"
                            :show-file-list="false"
                            name="files"
                        >
                            <el-button size="small" class="btn-greenYellow">
                                上传附件
                            </el-button>
                        </el-upload>
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="attachDownload"
                            v-if="attachSelection.length > 0"
                            >批量下载</el-button
                        >
                        <el-button
                            slot="reference"
                            size="small"
                            class="btn-delete"
                            v-if="attachSelection.length > 0 && !isView"
                            @click="deleteData"
                            >批量删除</el-button
                        >
                        <span
                            style="
                                margin: 0 0 0 10px;
                                color: #999;
                                line-height: 35px;
                            "
                            v-if="!isView"
                            >*仅支持上传图片、PDF格式，文件小于20M</span
                        >
                    </div>
                </div>
                <el-table
                    :data="attachTableData"
                    border
                    style="width: 100%"
                    @cell-mouse-enter="cellMouseEnter"
                    @cell-mouse-leave="cellMouseLeave"
                    :cell-class-name="cellClsNm"
                    @selection-change="attachSelectionChange"
                >
                    <el-table-column
                        show-overflow-tooltip
                        type="selection"
                        width="55"
                    >
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        type="index"
                        width="80"
                        label="序号"
                    >
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="objectPath"
                        width="200"
                        label="缩略图"
                    >
                        <template slot-scope="{ row }" :size="60">
                            <div style="display: flex; justify-content: center">
                                <el-image
                                    v-if="
                                        'jpg,jpeg,png'.includes(
                                            row.objectName
                                                .split('.')
                                                .pop()
                                                .toLowerCase()
                                        )
                                    "
                                    style="width: 100px; height: 100px"
                                    :src="row.objectPath"
                                    :preview-src-list="[row.objectPath]"
                                ></el-image>
                                <el-image
                                    v-else
                                    style="width: 100px; height: 100px"
                                    :src="pdfImg"
                                ></el-image>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="objectName"
                        label="文件名称"
                    >
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="objectSize"
                        label="文件大小"
                        width="120"
                    >
                        <template slot-scope="{ row }">
                            {{ bytesToSize(row.objectSize) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="gmtCreate"
                        width="200"
                        label="上传时间"
                    >
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="userName"
                        width="120"
                        label="上传人"
                    >
                    </el-table-column>
                    <div class="upload" slot="empty" v-if="!isView">
                        <!-- 机构简码暂时写死 orgCode: $store.state.userInfo.orgInfo.shortCode -->
                        <!-- orgCode: 'DQGSGJGSZCB1-1' -->
                        <el-upload
                            class="upload-demo"
                            drag
                            :action="uploadUrl"
                            :headers="{
                                token: userInfo.token,
                                org: encodeURIComponent(
                                    JSON.stringify(userInfo.orgInfo)
                                )
                            }"
                            :data="{
                                bucketName,
                                relationId,
                                orgCode
                            }"
                            :before-upload="beforeAvatarUpload"
                            multiple
                            :accept="accept"
                            :on-success="attachOnSuccess"
                            :show-file-list="false"
                            name="files"
                        >
                            <el-button type="primary" style="padding: 20px 80px"
                                >上传附件</el-button
                            >
                            <div
                                style="
                                    margin-top: 10px;
                                    line-height: 25px;
                                    font-size: 12px;
                                "
                            >
                                鼠标拖入上传，按住Ctrl可多选附件<br />
                                *仅支持上传图片、PDF格式，文件小于20M
                            </div>
                        </el-upload>
                    </div>
                </el-table>

                <com-pagination
                    v-if="total"
                    :total="total"
                    :pageSize.sync="pageSize"
                    :currentPage.sync="currentPage"
                    :tableData.sync="attachTableData"
                />
            </div>
            <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
                <el-button type="primary" @click="dialogVisible = false"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import service from '@/utils/request'
import { oss } from '@/utils/request'
import ossRequest from '@/api/oss/oss'
import ComPagination from '@/components/pagination/pagination'
import { bytesToSize, showLoading, hideLoading, batchDownload } from '@/utils/common'
import pdfImg from '@/assets/pdf_icon.png'
import { mapState } from 'vuex'
export default {
    props: {
        bucketName: {
            type: String,
            default: '',
            require: true
        },
        relationId: {
            type: String,
            default: '',
            require: true
        },
        isView: {
            type: Boolean,
            default: false
        },
        uploadVisible: {
            type: Boolean,
            default: false
        },
    },
    components: {
        ComPagination
    },
    data () {
        return {
            uploadUrl: 'api/oss/uploader',
            attachTableData: [],
            attachSelection: [],
            pageSize: 10, // 每页显示条目个数
            currentPage: 1,
            total: 0,
            accept: '.jpg,jpeg,.png,.pdf',
            pdfImg,
            dialogVisible: false,
            oss: oss
        }
    },
    computed: {
        ...mapState(['userInfo']),
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
        // attachTableDataShow () {
        //     const start = (this.currentPage - 1) * this.pageSize
        //     return this.attachTableData.slice(start, start + this.pageSize)
        // }
    },
    watch: {
        uploadVisible () {
            this.dialogVisible = this.uploadVisible
        }
    },
    async created () {
        showLoading()
        await this.getObjectByRelationId()
        hideLoading()
    },
    methods: {
        deleteData () {
            const length = this.attachSelection.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？数据删除后不可恢复，请谨慎操作！`,
                this.attachDel
            )
        },
        attachDownload () {
            // console.log(this.attachSelection)
            // const promiseArr = []
            // this.attachSelection.forEach(item => {
            //     promiseArr.push(this.downloadFile(item))
            // })
            // Promise.all(promiseArr)
            const fileList = this.attachSelection.map(item => {
                return {
                    objectName: item.objectName,
                    objectPath: item.objectPath
                }
            })
            batchDownload(fileList)
        },
        attachSelectionChange (selection) {
            this.attachSelection = selection
        },
        attachDel () {
            const recordIds = this.attachSelection.map(value => value.recordId)
            const promiseArr = []
            showLoading()
            recordIds.forEach(value => {
                promiseArr.push(
                    ossRequest.deleterRecordId({ recordId: value })
                )
            })
            Promise.all(promiseArr)
                .then(() => {
                    this.clientPop(
                        'suc',
                        '删除成功',
                        this.getObjectByRelationId
                    )
                })
                .catch(() => {
                    this.clientPop(
                        'err',
                        '部分数据删除失败',
                        this.getObjectByRelationId
                    )
                })
                .finally(() => {
                    hideLoading()
                })
        },
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20
            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    this.attachTableData = res
                    this.total = res.length
                })
        },
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        cellMouseEnter () {},
        cellMouseLeave () {},
        cellClsNm () {
            return ''
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        downloadIamge (imgsrc, fileName) {
            //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {
                    // if browser is IE
                    navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        async downloadFile (obj) {
            const url = oss + obj.objectPath
            const fileNameFull = obj.originalObjectName
            const fileExt = fileNameFull.split('.').pop()
            if (
                ['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(
                    fileExt.toLowerCase()
                ) === -1
            ) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
        },
        dialogOpen () {
            this.getObjectByRelationId()
        },
        handleClose () {
            this.$emit('update:uploadVisible', false)
        }
    }
}
</script>
<style lang="scss" scoped>
.e-table {
    background-color: auto;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 10px 0 0;
}

::v-deep .e-form .header .el-dialog__header{
    padding: 5px !important
}
</style>
